package com.fingard.dsp.bank.directbank.bob01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.abc02.ABC02Header;
import com.fingard.dsp.bank.directbank.bankInterface.IContract;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.fngrd01.FnGrd01Header;
import com.fingard.dsp.bank.reqrespobj.contract.*;
import com.fingard.dsp.bank.reqrespobj.contract.detail.RetAtsContractDetail;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

public class BOB01Contract extends BOB01Base implements IContract {
    public RetAtsContract contract(ReqContract p_req) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_req.reqHeader);
        RetAtsContractDetail retDetail = new RetAtsContractDetail(p_req);

        try {
            String opName = "";
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter);
            if ("01".equals(p_req.contractDetail.step)) {
                opName = "CebankIdentityOp";
                xmlWriter.writeStartElement("opReq");
                xmlWriter.writeElementString("opName", opName);
                xmlWriter.writeElementString("serialNo", p_req.contractDetail.askNumber);
                xmlWriter.writeElementString("reqTime", Format.Date8Format.format(new Date()));
                xmlWriter.writeStartElement("ReqParam");
                xmlWriter.writeElementString("accountNo", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("accName", p_req.contractDetail.payName);
                xmlWriter.writeElementString("idNo", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("mobile", p_req.contractDetail.cellPhone);
                String payuse = "";
                String batBusiType = getBankConfig().getSetValue("businessType", "Memo", "contract");
                if (StringHelper.hasAnyChar(batBusiType)) {
                    payuse = getBankConfig().getMapValueByKey("payUseCode", p_req.contractDetail.srcXElement.getSingleText(batBusiType));
                } else {
                    payuse = "保险";// 默认值:保险
                }
                xmlWriter.writeElementString("payuse", payuse);
                xmlWriter.writeElementString("agreementno", p_req.contractDetail.askNumber);
                xmlWriter.writeElementString("scno", "0");
                xmlWriter.writeElementString("payEffectiveBeginDate", Format.Date8Format.format(new Date()));//扣款有效期起始日期

                String deadLine = p_req.contractDetail.deadLine;
                if (StringHelper.isNullOrEmpty(deadLine)) {
                    deadLine = getBankConfig().getMapValueByKey("contractKeyMapping", "deadLine");
                }
                xmlWriter.writeElementString("payEffectiveEndDate ", deadLine);//扣款有效期结束日期

                String singleLimit = p_req.contractDetail.singleLimit;
                if (StringHelper.isNullOrEmpty(singleLimit)) {
                    singleLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "singleLimit");
                }
                xmlWriter.writeElementString("singleLimit", StringHelper.amountMultiply100(singleLimit));//单笔限额，最大长度为16位无符号数字串，后两位表示小数（如：1601表示16.01）

                String dayAmtLimit = p_req.contractDetail.dayAmtLimit;
                if (StringHelper.isNullOrEmpty(dayAmtLimit)) {
                    dayAmtLimit = getBankConfig().getMapValueByKey("contractKeyMapping", "dayAmtLimit");
                }
                xmlWriter.writeElementString("dayLimit", StringHelper.amountMultiply100(dayAmtLimit));//日累计限额，最大长度为16位无符号数字串，后两位表示小数（如：1601表示16.01）
                xmlWriter.writeEndDocument();
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = "北京银行暂只支持用户回复短信确认";
                retAts.writeRetDetail(retDetail);
                return retAts;
            }

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);//发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/BCCBEBankData/opRep/retCode");
                    String tmpErrMsg = tmpBkReader.getFirstText("/BCCBEBankData/opRep/errMsg");

                    retDetail.respCode = "0";
                    retDetail.signConfirmType = "3";
                    retDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRetCode);
                    retDetail.respInfo = tmpErrMsg;

                    if (tmpRetCode.equals("0")) {
                        retDetail.authCode = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/agreementno");
                    }
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsContract upContract(ReqContract p_req) throws Exception {
        return null;
    }


    public RetAtsContract qryContract(ReqContract p_reqQry) throws Exception {
        RetAtsContract retAts = new RetAtsContract(p_reqQry.reqHeader);
        RetAtsContractDetail retDetail = new RetAtsContractDetail(p_reqQry);

        try {
            String opName = "CebankqueryIdentityOp";
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("opReq");
            xmlWriter.writeElementString("opName", opName);
            xmlWriter.writeElementString("serialNo", p_reqQry.contractDetail.askNumber);
            xmlWriter.writeElementString("reqTime", Format.Date8Format.format(new Date()));
            xmlWriter.writeStartElement("ReqParam");
            xmlWriter.writeElementString("accountNo", p_reqQry.contractDetail.payAct);
            xmlWriter.writeElementString("accName", p_reqQry.contractDetail.payName);
            xmlWriter.writeElementString("idNo", p_reqQry.contractDetail.certNum);
            xmlWriter.writeElementString("mobile", p_reqQry.contractDetail.cellPhone);
            xmlWriter.writeElementString("agreementno", p_reqQry.contractDetail.askNumber);
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);//发送银行

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/BCCBEBankData/opRep/retCode");
                    String tmpErrMsg = tmpBkReader.getFirstText("/BCCBEBankData/opRep/errMsg");

                    retDetail.respCode = "0";
                    retDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", tmpRetCode);
                    retDetail.respInfo = tmpErrMsg;

                    if (tmpRetCode.equals("0")) {
                        retDetail.authCode = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/agreementno");
                        String result = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/result");
                        if ("5".equals(result)) {
                            retDetail.signState = ContractState.SUCCESS;
                        } else if ("1".equals(result) || "3".equals(result) || "6".equals(result) || "7".equals(result) || "8".equals(result)) {
                            retDetail.signState = ContractState.FAIL;
                        } else {
                            retDetail.signState = ContractState.SIGNING;
                        }
                        retDetail.deadLine = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/payEffectiveEndDate ");
                        retDetail.singleLimit = tmpBkReader.getFirstText("/BCCBEBankData/opRep/opResult/singleLimit ");
                    }

                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            retDetail.respCode = "-1";
            retDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    public RetAtsQryBatContract qryBatContract(ReqQryBatContract p_reqQry) throws Exception {
        return null;
    }

}
